package com.dd.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.common.constans.RedisFileKey;
import com.dd.common.constans.TokenConstantKey;
import com.dd.common.expection.BizException;
import com.dd.common.response.ResultCode;
import com.dd.common.struct.FileVoCover;
import com.dd.mapper.FolderMapper;
import com.dd.mapper.UserFoldFileMapper;
import com.dd.pojo.bo.FileBO;
import com.dd.pojo.entry.File;
import com.dd.pojo.entry.Folder;
import com.dd.pojo.entry.UserFoldFile;
import com.dd.pojo.entry.UserShare;
import com.dd.pojo.query.ShareFIleQuery;
import com.dd.pojo.vo.ShareFileVo;
import com.dd.service.UserShareService;
import com.dd.mapper.UserShareMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


@Service
@RequiredArgsConstructor
public class UserShareServiceImpl extends ServiceImpl<UserShareMapper, UserShare>
    implements UserShareService{


    private final FileVoCover fileVoCover;

    private final RedisTemplate redisTemplate;


    private final UserFoldFileMapper userFoldFileMapper;


    private final FolderMapper folderMapper;


   final static String SHARE_PROFIX="http://154.221.19.26:8082/shareFile/";
    @Override
    public String shareFile(String userId, String userName, ShareFileVo fileVos) {


        UserShare shareInfo = fileVoCover.entity2UserShareFile(fileVos);
        String uuid = UUID.randomUUID().toString();

        shareInfo.setShareUserId(userId).setShareUserName(userName).setShareUuid(uuid)
                .setShareCreateTime(LocalDateTime.now())
                .setSharePath(SHARE_PROFIX+uuid);
        baseMapper.insert(shareInfo);


        if(fileVos.getLoseData()>0){
            shareInfo.setShareLoseTime(shareInfo.getShareCreateTime().plusDays(fileVos.getLoseData()));
        }

        redisTemplate.opsForValue().set(RedisFileKey.FILE_SHARE_KEY+uuid, JSONUtil.toJsonStr(shareInfo));
        return SHARE_PROFIX+uuid;
    }

    @Override
    public UserShare findShareFile(String uuid) {
      Object share2 = redisTemplate.opsForValue().get(RedisFileKey.FILE_SHARE_KEY+uuid);

        UserShare share = JSONUtil.parse(share2).toBean(UserShare.class);
        if(Objects.isNull(share)){
            UserShare share1 = baseMapper.selectById(uuid);
            checkShareFile(share1);
            redisTemplate.opsForValue().set(RedisFileKey.FILE_SHARE_KEY+uuid, JSONUtil.toJsonStr(share1));

            return  share1;
        }
        checkShareFile(share);

        return  share;

    }

    @Override
    public  List<FileBO> findFile(ShareFIleQuery query) {
        ArrayList<FileBO> list = new ArrayList<>();
        //分两种情况查询
        //1 查询文件
        if(query.getType()==0){
            UserFoldFile userFoldFile = userFoldFileMapper.selectOne(new LambdaQueryWrapper<UserFoldFile>().eq(UserFoldFile::getFileId, query.getFid()).eq(UserFoldFile::getUserId, query.getUid()));
             list.add(fileVoCover.entity2FiletoBo(userFoldFile));
            return list;
        }
        //查询文件夹

       // UserFoldFile userFoldFile = userFoldFileMapper.selectOne(new LambdaQueryWrapper<UserFoldFile>().eq(UserFoldFile::getFolderId, query.getFid()).eq(UserFoldFile::getUserId, query.getUid()));

        Folder folder = folderMapper.selectById(query.getFid());
        list.add(fileVoCover.entity2FoldtoBo(folder));
        return list;

    }

    @Override
    public List<FileBO> findUserFiles(String foldId, String uid) {

        List<FileBO> list = new ArrayList<>();

        //先查询属于该文件夹的子文件夹
        List<Folder> folders = folderMapper.selectList(new LambdaQueryWrapper<Folder>().eq(Folder::getParentID, foldId));

        if(!CollectionUtils.isEmpty(folders)){


            for(Folder fold:folders){
                FileBO boss = fileVoCover.entity2FoldtoBo( fold);
                list.add(boss);
            }

        }

        List<UserFoldFile> files = userFoldFileMapper.selectList(new LambdaQueryWrapper<UserFoldFile>().isNotNull(UserFoldFile::getFileId).eq(UserFoldFile::getFolderId, foldId).eq(UserFoldFile::getUserId, uid));


        if(!CollectionUtils.isEmpty(files)){


            for(UserFoldFile file:files){
               FileBO boss = fileVoCover.entity2FiletoBo( file);
                list.add(boss);
            }

        }


        return list;
    }

    @Override
    public List<UserShare> findFiles(String userID) {

        List<UserShare> userShares = baseMapper.selectList(new LambdaQueryWrapper<UserShare>().eq(UserShare::getShareUserId, userID));

        if(!CollectionUtils.isEmpty(userShares)){

            for(UserShare share:userShares){

                if(share.getShareDate()>0){
                    LocalDateTime dateTime = share.getShareCreateTime().plusDays(share.getShareDate());
                    share.setShareLoseTime(dateTime);
                    share.setLose(dateTime.isBefore(LocalDateTime.now()));


                }
            }
        }

        return userShares;
    }


    private void checkShareFile(UserShare file){
        if(Objects.isNull(file)){
            throw  new BizException(ResultCode.SHARE_FILE_CANCEL);
        }

        if(file.getShareDate()==-1){
            throw  new BizException(ResultCode.SHARE_FILE_TIME);
        }
        if(file.getShareDate()>0){
            LocalDateTime dateTime = file.getShareCreateTime().plusDays(file.getShareDate());
            //校验链接是否已经失效
            boolean before = dateTime.isBefore(LocalDateTime.now());
            if(before){
                throw new BizException(ResultCode.SHARE_FILE_TIME);
            }
        }
    }
}




